﻿#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Script.Services;
using System.Web.Services;

#endregion

namespace ProcolServices {
    /// <summary>
    /// Summary description for MajorService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [ScriptService]
    public class MajorService : WebService {
        private readonly ProcolDataContext db = new ProcolDataContext();

        [WebMethod]
        public String[] GetMajors(string prefixText, int count) {
            var query = (from m in db.Majors
                         where
                                 m.LanguageId == count &&
                                 (m.MajorId.Contains(prefixText.Trim()) || m.Text.Contains(prefixText.Trim()))
                         select String.Join(" ", new[] {m.MajorId, "-", m.Text}));

            return query.Take(10).ToArray();
        }

        [WebMethod]
        public String[][] GetAllMajors(int language) {
            var query = (from m in db.Majors
                         orderby m.Text
                         where m.LanguageId == language
                         select new[] {m.MajorId, String.Join(" ", new[] {m.MajorId, "-", m.Text})});

            return query.ToArray();
        }

        [WebMethod]
        public UserService.IntString[] GetSchools() {
            var schools = new List<UserService.IntString>();
            var query = (from s in db.Schools
                         select new {s.SchoolId, s.Name});


            foreach (var s in query)
                schools.Add(new UserService.IntString {Int = s.SchoolId, Str = s.Name});

            return schools.ToArray();
        }

        [WebMethod]
        public int AddNewMejor(String majorId, int languageId, String text) {
            var values = new Object[] {majorId, languageId, text};

            foreach (var value in values) {
                String str = value.ToString();
                int tryParse;

                if (Int32.TryParse(str, out tryParse)) {
                    if (tryParse < 0)
                        return -2;
                } else if (String.IsNullOrEmpty(str))
                    return -2;
            }

            try {
                var newMajor = new Major {MajorId = majorId, LanguageId = languageId, Text = text};
                db.Majors.InsertOnSubmit(newMajor);
                db.SubmitChanges();

                return newMajor.LanguageId;
            } catch (InvalidOperationException) {
                return -2;
            }
        }
    }
}